const { DataTypes } = require("sequelize");
const { isNull, len, isValidIDCard } = require("../valid");

module.exports = (app) => {
  const { STRING, INTEGER, ENUM } = app.Sequelize;

  const User = app.model.define(
    "user",
    {
      id: {
        type: DataTypes.UUID, // 修改为UUID类型
        defaultValue: DataTypes.UUIDV4, // 设置默认值为生成的UUIDv4
        primaryKey: true,
      },
      type: {
        type: ENUM("normal", "admin"),
        defaultValue: "normal",
      },
      account: {
        type: STRING,
        validate: {
          custom: async (account) => {
            const user = await User.findOne({ where: { account, isDeleted: 0 } });
            if (user) {
              throw new Error("此账号已注册~");
            }
          },
        },
        allowNull: false,
      },
      name: {
        type: STRING(100),
        validate: {
          fn: (value) => isNull(value, "姓名"),
        },
        allowNull: false,
      },

      password: {
        type: STRING(),
        validate: {
          fn: (value) =>
            len(value, {
              min: 6,
              max: 20,
              text: "密码",
            }),
        },
        allowNull: false,
      },
      avatar: {
        type: STRING(256),
        allowNull: true,
      },
      idNumber: {
        type: STRING(32),
        allowNull: true,
        validate: {
          fn: isValidIDCard,
        },
      },
      gender: {
        type: ENUM("男", "女"),
        allowNull: true,
      },
      workUnit: {
        type: STRING(256),
        allowNull: true,
      },
      position: {
        type: STRING(256),
        allowNull: true,
      },
      isDeleted: {
        type: INTEGER,
        defaultValue: 0,
      },
    },
    {
      timestamps: true,
      underscored: false,
      hooks: {
        beforeCreate: async (instance, options) => {
          await validateAccount(instance);
        }
      },
    }
  );

  async function validateAccount(instance) {
    if (instance.type === "normal") {
      const emailRegex = /^[\w.-]+@[\w-]+(\.[\w-]+)+$/;
      const phoneRegex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;

      if (!emailRegex.test(instance.account) && !phoneRegex.test(instance.account)) {
        throw new Error("请提供正确的邮箱或手机号!");
      }
    }
  }

  return User;
};
